package com.tyrone.concurrent.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Condition接口与实例
 * Condition实现等待/通知
 * @author Tyrone
 * @date 2021/12/20 1:10
 */
public class ConditionUseCase {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    /**
     * 等待
     * @throws InterruptedException
     */
    public void conditionWait() throws InterruptedException{
        lock.lock();
        try{
            condition.await();  //await()会释放锁 ，调用线程会将会等待
        }finally {
            lock.unlock();
        }
    }

    /**
     * 通知
     * @throws InterruptedException
     */
    public void conditionSignal() throws InterruptedException{
        lock.lock();
        try {
            condition.signal(); //通知24行的等待线程，等待线程从await()方法中返回。并且，等待线程将会获取到锁
        }finally {
            lock.unlock();
        }
    }

}
